package com.example.serverjava.utils;

import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public  class ServerUtil {

    /**
     * 获取IP地址
     *
     * @return
     */
    public static String getIpAddr() throws IOException {
        return InetAddress.getLocalHost().getHostAddress();
    }

    /**
     * 获取linuxShell命令结果. 字符串
     *
     * @param cmd 指令
     * @return 指令结果
     */
    public static String getRuntimeExec(final String cmd) {
        BufferedReader bufferedReader = null;
        Process process = null;
        StringBuffer sb = new StringBuffer();
        try {
            String buffer;
            //System.out.println(cmd);
            process = Runtime.getRuntime().exec(cmd);
            // 得到结果
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((buffer = bufferedReader.readLine()) != null) {
                sb.append(buffer + "\n");
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            return sb.toString();
        } catch (IOException e) {
            System.out.println("execute failed.");
            return null;
        } finally {
            // 清理
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取linuxShell命令结果.  数组
     *
     * @param cmd 指令
     * @return 指令结果
     */
    public static String getRuntimeExec(final String[] cmd) {
        BufferedReader bufferedReader = null;
        Process process = null;
        StringBuffer sb = new StringBuffer();
        try {
            String buffer;
            //System.out.println(cmd);
            process = Runtime.getRuntime().exec(cmd);
            // 得到结果
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((buffer = bufferedReader.readLine()) != null) {
                sb.append(buffer + "\n");
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            return sb.toString();
        } catch (IOException e) {
            System.out.println("execute failed.");
            return null;
        } finally {
            // 清理
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                    bufferedReader = null;
                }
                if (process != null) {
                    process.destroy();
                    process = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 配置ip地址、子网掩码、网关、DNS
     * @param addr
     * @param type
     */
    public static void setConfigure(String addr,String type){
        try {
            String networkName = getNetworkCardConfigureName();
            // 添加新配置
            String newStr = "echo '"+type+"=\""+ addr +"\"'>>/etc/sysconfig/network-scripts/ifcfg-"+networkName;
            System.out.println(newStr);
            String[] cmmd2 = new String[]{"/bin/sh","-c",newStr};
            Runtime.getRuntime().exec(cmmd2);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *  删除原来的配置
     * @param type
     */
    public static void delConfigure(String type){
        try {
            String networkName = getNetworkCardConfigureName();
            // 删除原来的配置
            String oldStr = "sed -i '/"+type+"/d' /etc/sysconfig/network-scripts/ifcfg-"+networkName;
            String[] cmmd = new String[]{"/bin/sh","-c",oldStr};
            Runtime.getRuntime().exec(cmmd);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取ip地址、子网掩码、网关、DNS
     */
    public static String getConfigure(String type,String networkName){
        String str = getRuntimeExec("cat  /etc/sysconfig/network-scripts/ifcfg-"+networkName+"");
        if (StringUtils.hasText(str)) {
            String[] split = str.split("\n");
            List<String> addr = Arrays.stream(split).filter(s -> s.contains(type))
                    .collect(Collectors.toList());
            if (addr.size() == 0) {
                return "";
            }
            String resultStr = addr.get(0).split("=\"")[1];
            return resultStr.substring(0, resultStr.length()-1);
        }
        return "";
    }


    /**
     * 获取网卡配置名称列表
     */
    public static List<String> getNetworkCardConfigureNameList(){
        String oldStr = "find /etc/sysconfig/network-scripts/ -name 'ifcfg-e*'";
        String[] cmmd = new String[]{"/bin/sh","-c",oldStr};
        String resultCmd = getRuntimeExec(cmmd);
        String[] resultArr = resultCmd.split("\n");
        List<String> list = new ArrayList<>();
        for (String s : resultArr) {
            list.add(s.split("/")[s.split("/").length - 1].split("-")[1]);
        }
        return list;

    }

    /**
     * 获取正在使用的网卡配置名称
     */
    public static String getNetworkCardConfigureName(){
        List<String> list = getNetworkCardConfigureNameList();
        String oldStr = "cat /proc/net/dev";
        String[] cmmd = new String[]{"/bin/sh","-c",oldStr};
        String str = getRuntimeExec(cmmd);
        String[] split = str.split("\n");
        List<String> strList = new ArrayList<>();
        for (String s : split) {
            for (String s1 : list) {
                if (s.contains(s1)){
                    strList.add(s.trim());
                }
            }
        }
        String result = "";
        for (String ss : strList) {
            String[] sArr = ss.split(":");
            String s = sArr[1];
            if (s.contains("1") ||s.contains("2") || s.contains("3") ||s.contains("4") ||s.contains("5") || s.contains("6")){
                result =  sArr[0];
            }
        }
        return result;
    }

    /**
     * 重启网络
     */
    public static void restartNetwork(){
        getRuntimeExec("systemctl restart network");
    }

    /**
     * 重新启动
     */
    public static void reboot(){
        getRuntimeExec("shutdown -r now");
    }
    /**
     * 关机
     */
    public static void shutdown(){
        getRuntimeExec("shutdown -h now");
    }

    /**
     * Ip校验
     * @param ipAddress 单个ip
     * @return
     */
    public static boolean isValidIPAddress(String ipAddress) {
        if ((ipAddress != null) && (!ipAddress.isEmpty())) {
            return Pattern.matches("^192\\.168(\\.(\\d|([1-9]\\d)|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))){2}$", ipAddress);
//            return Pattern.matches("^([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$", ipAddress);
        }
        return false;
    }

    public static void main(String[] args) {
        String a = "DNS1=\"114.114.114.114\"";
        String[] split = a.split("=\"");
        for (String s : split) {
            System.out.println(s.substring(0, s.length()-1));
        }
    }

}
